package com.chengxiaoxiao.libarypartner.fragment;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.chengxiaoxiao.libarypartner.R;
import com.chengxiaoxiao.libarypartner.activity.LoginActivity;
import com.chengxiaoxiao.libarypartner.activity.MyBorrowActivity;
import com.chengxiaoxiao.libarypartner.activity.PersonActivity;
import com.chengxiaoxiao.libarypartner.constants.AppConsrants;
import com.chengxiaoxiao.libarypartner.constants.Consrants;
import com.chengxiaoxiao.libarypartner.domain.UpdateAppInfo;
import com.chengxiaoxiao.libarypartner.utils.ApiAddress;
import com.chengxiaoxiao.libarypartner.utils.ApkInfoUtils;
import com.chengxiaoxiao.libarypartner.utils.LoginUtils;
import com.chengxiaoxiao.libarypartner.utils.SPUtils;
import com.chengxiaoxiao.libarypartner.utils.ToastUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class InfoFragment extends Fragment
{
    private ImageView imageUser;
    private ListView listView;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

        //跳转到登陆界面
        boolean isLogin =LoginUtils.getLoginStatus(getActivity());

        if(!isLogin)
        {
            startActivity(new Intent(getActivity(), LoginActivity.class));

        }



        View view = inflater.inflate(R.layout.fragment_info, container, false);

        imageUser = (ImageView) view.findViewById(R.id.imageUser);
        listView = (ListView) view.findViewById(R.id.listViewInfo);

        listView.setAdapter(new MyAdapter());



        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.user, null);
        imageUser.setImageBitmap(bitmap);


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {

                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                switch (position)
                {
                    case 0:
                        //个人信息
                        startActivity(new Intent(getActivity(), PersonActivity.class));

                        break;
                    case 1:
                        //我的借阅
                        startActivity(new Intent(getActivity(), MyBorrowActivity.class));
                        break;
                    case 2:
                        checkUpdate();
                        break;
                    case 3:

                        dialog.setTitle("提示信息");
                        dialog.setMessage("确定要退出登录吗");
                        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                SPUtils.putString(Consrants.SP_LOGIN_USERNAME,"",getActivity());
                                SPUtils.putString(AppConsrants.BORROW_LIST_ID,"",getActivity());
                                LoginUtils.setLoginStatusFalse(getActivity());
                                startActivity(new Intent(getActivity(),LoginActivity.class));
                                getActivity().onBackPressed();

                            }
                        });
                        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {

                            }
                        });

                        dialog.show();

                        break;


                }

            }
        });


        return view;
    }

    /**
     * 检查更新
     */
    private void checkUpdate()
    {


        final AsyncHttpClient client = new AsyncHttpClient();
        client.get(ApiAddress.getApiDomain() + "/client/ClientServlet?op=getnewVersion", new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {
                UpdateAppInfo info = new UpdateAppInfo();
                String body = new String(responseBody);
                try
                {
                    //versionName:"1.0","versionCode":2,des:"描述",url:"下载地址"
                    JSONObject jsonObj = new JSONObject(body);
                    String versionName = jsonObj.getString("versionName");
                    int versionCode = jsonObj.getInt("versionCode");
                    String url = jsonObj.getString("url");
                    String des = jsonObj.getString("des");

                    info.setDes(des);
                    info.setUrl(url);
                    info.setVersionCode(versionCode);
                    info.setVersionName(versionName);


                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                //显示弹窗
                showUpdateDialog(info);

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                //LoadDialogUtils.hidden();
                ToastUtils.makeText(getActivity(), "获取新版本失败");


            }
        });


    }

    /**
     * 弹出更新弹窗
     */
    private void showUpdateDialog(final UpdateAppInfo infos)
    {

        final UpdateAppInfo info = infos;

        if (info.getVersionCode() > ApkInfoUtils.getVersionCode(getActivity()))
        {

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("发现新版本" + info.getVersionName());
            builder.setMessage(info.getDes());

            builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    String path = getActivity().getExternalCacheDir() + "/libary.apk";

                    ToastUtils.makeText(getActivity(), "后台下载中....");

                    File file = new File(path);
                    if(file.exists())
                    {
                        file.delete();
                    }


                    HttpUtils utils = new HttpUtils();

                    utils.download(ApiAddress.getDomain() + info.getUrl(), path, true, new RequestCallBack<File>()
                    {
                        @Override
                        public void onSuccess(ResponseInfo<File> responseInfo)
                        {


                            // 下载成功
                            String p = responseInfo.result.getAbsolutePath();


                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            Uri data;
                            // 判断版本大于等于7.0
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            {
                                // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
                                data = FileProvider.getUriForFile(getActivity(), "com.chengxiaoxiao.fileProvider", responseInfo.result);
                                // 给目标应用一个临时授权
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            } else
                            {
                                data = Uri.fromFile(responseInfo.result);
                            }
                            intent.setDataAndType(data, "application/vnd.android.package-archive");

                            getActivity().startActivityForResult(intent,0);
                            //
                            //                            // 跳转系统安装页面
                            //                            Intent intent = new Intent();
                            //                            intent.setAction(Intent.ACTION_VIEW);
                            //                            intent.addCategory(Intent.CATEGORY_DEFAULT);
                            //                            intent.setDataAndType(Uri.fromFile(responseInfo.result), "application/vnd.android.package-archive");
                            //                            startActivityForResult(intent, 0);


                        }

                        @Override
                        public void onFailure(HttpException e, String s)
                        {
                            ToastUtils.makeText(getActivity(), s);

                        }

                        @Override
                        public void onStart()
                        {
                            super.onStart();

                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading)
                        {
                            long percent =current/total;


                        }
                    });
                }
            });

            builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {

                }
            });

            builder.show();

        } else
        {

            ToastUtils.makeText(getActivity(),"当前已经是最新版本了");
        }
    }




    private int[] icons = {R.drawable.person_info, R.drawable.person_system, R.drawable.person_update, R.drawable.person_out};
    private String[] functions = {"个人信息", "我的借阅", "更新", "退出"};


    public class MyAdapter extends BaseAdapter
    {
        @Override
        public int getCount()
        {
            return functions.length;
        }

        @Override
        public Object getItem(int i)
        {
            return functions[i];
        }

        @Override
        public long getItemId(int i)
        {
            return i;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup)
        {

            View v;
            if (convertView == null)
            {
                v = View.inflate(getActivity(), R.layout.list_item_info, null);
            } else
            {
                v = convertView;
            }

            ImageView imgIcon = (ImageView) v.findViewById(R.id.imgIcon);
            TextView textName = (TextView) v.findViewById(R.id.textName);

            imgIcon.setImageResource(icons[position]);
            textName.setText(functions[position]);

            return v;
        }
    }


    /**
     * 个人信息的文字和图标
     * @return
     */
    private List<Map<String, Object>> getData()
    {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", "个人信息");
        map.put("img", R.drawable.a);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("title", "设置");
        map.put("img", R.drawable.a);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("title", "更新");
        map.put("img", R.drawable.a);
        list.add(map);
        map = new HashMap<String, Object>();
        map.put("title", "退出");
        map.put("img", R.drawable.a);
        list.add(map);

        return list;
    }


}
